package utils

import _map "mlgmd.com/hearsay/utils/map"

func Keys[K comparable, V any](m map[K]V) (res []K) {
	return _map.Keys(m)
}

func Values[K comparable, V any](m map[K]V) (res []V) {
	return _map.Values(m)
}

func MapByFunc[K comparable, V any](s []V, h func(v V) K) (res map[K]V) {
	res = map[K]V{}
	for _, v := range s {
		res[h(v)] = v
	}
	return
}

type KeyProvider interface {
	Key(k string) int
}

// MapByKey 通过指定的Key将切片转变成map
func MapByKey[V KeyProvider](s []V, ks ...string) (res map[int]V) {
	k := append(ks, "")[0]
	res = map[int]V{}
	for _, v := range s {
		res[v.Key(k)] = v
	}
	return
}

func GroupByKey[V KeyProvider](s []V, ks ...string) (res map[int][]V) {
	k := append(ks, "")[0]
	res = map[int][]V{}
	for _, v := range s {
		k := v.Key(k)
		es, has := res[k]
		if !has {
			es = make([]V, 0)
		}
		es = append(es, v)
		res[k] = es
	}
	return
}

func KeyOfSlice[V KeyProvider](s []V, k string) (res []int) {
	res = make([]int, len(s))
	for i, v := range s {
		res[i] = v.Key(k)
	}
	return res
}

func Key[V KeyProvider](k string) func(v V) int {
	return func(v V) int {
		return v.Key(k)
	}
}
